import { v4 as uuidv4 } from 'uuid';
import type { OpinionProgrammeBook } from '@fill/client';
import dayjs from 'dayjs';
import { keyBy } from 'lodash';
import { DATA_SOURCE, FILL_NAME, FILL_TABLE_COLLECTION, INodeState, LANHAI_SYSTEM, NODE_TYPE, PROGRAMME_TEXT, STATUS_VALUE, TABLE_COLLECTION } from '../../constants/default';
import type { w_zgfa } from '../types/zgfa';
import { CONFIG_KEYS } from '../../constants/config';
import { now } from '../../util/helper';
import type { w_sp_history } from '../types/sp_history';
import type { IImportSchema, ILanhaiDataSchema, ILanhaiSpDef, ILanhaiSpNode, IPipe, IRecordSchemas } from './interface';
import { Pipe } from './pipe';

export class Programme extends Pipe implements IPipe {
  async import(data: ILanhaiDataSchema, sp_def: ILanhaiSpDef, sp_node: ILanhaiSpNode) {
    if (!sp_node[NODE_TYPE.PROGRAMME])
      return [];
    const programme_map = sp_node[NODE_TYPE.PROGRAMME];
    console.log(programme_map);

    let programmes = Object.values(programme_map).map((item) => {
      return {
        uuid: item.F_REL_ID_,
        node: item.F_DEF_ID_,
        next: item.F_NEXT_ || '',
        node_id: item.ID_,
        state: item.F_STATE_,
        status: '',
        note: '',
      };
    });

    if (data.has(TABLE_COLLECTION.SP_HISTORY)) {
      const history = data.get(TABLE_COLLECTION.SP_HISTORY)?.data as w_sp_history[];

      const history_collect = keyBy(history, 'F_NODE_ID_');

      console.log(history_collect);
      programmes = programmes.map((item) => {
        item.note = history_collect[item.node_id].F_SPYJ_ || '';

        return item;
      });
    }

    const results = {
      module: FILL_TABLE_COLLECTION.PROGRAMME,
      main: true,
      text: [PROGRAMME_TEXT],
      data: programmes,
    } as IImportSchema;
    console.log(results);
    return Promise.resolve([
      results,
    ]);
  }

  async export(sp_def: ILanhaiSpDef) {
    const { opinion, config } = this.data;
    const xczdx_ref_id = config[CONFIG_KEYS.F_XCZDX_REF_ID_]?.value || 'demo';

    const data: IRecordSchemas = {
      w_zgfa: {
        module: 'programme',
        table: TABLE_COLLECTION.PROGRAMME,
        path: FILL_NAME,
        main: true,
        data: [],
        data_source: DATA_SOURCE.BZXC_DADA,
        pk: 'ID_',
        table_desc: PROGRAMME_TEXT,
        table_name: TABLE_COLLECTION.PROGRAMME,
      },
      w_zgfa_ls: {
        module: 'programme',
        table: TABLE_COLLECTION.PROGRAMME_LS,
        path: FILL_NAME,
        main: false,
        data: [],
        data_source: DATA_SOURCE.BZXC_DADA,
        pk: 'ID_',
        table_desc: '',
        table_name: TABLE_COLLECTION.PROGRAMME_LS,
      },
      w_sp_node: {
        module: 'node',
        table: TABLE_COLLECTION.SP_NODE,
        path: FILL_NAME,
        main: false,
        data: [],
        data_source: DATA_SOURCE.BZXC_DADA,
        pk: 'ID_',
        table_desc: '',
        table_name: TABLE_COLLECTION.SP_NODE,
      },
      w_sp_history: {
        module: 'record',
        table: TABLE_COLLECTION.SP_HISTORY,
        path: FILL_NAME,
        main: true,
        data: [],
        data_source: DATA_SOURCE.BZXC_DADA,
        pk: 'ID_',
        table_desc: '',
        table_name: TABLE_COLLECTION.SP_HISTORY,
      },
      sys_file: {
        module: 'lanhai',
        table: TABLE_COLLECTION.SYS_FILE,
        path: LANHAI_SYSTEM,
        main: false,
        data: [],
        data_source: DATA_SOURCE.LANHAI_SYSTEM,
        pk: 'FILE_ID_',
        table_desc: '',
        table_name: TABLE_COLLECTION.SYS_FILE,
      },
    };

    opinion.filter(item => item.programme_book?.status === STATUS_VALUE.PROCESSED).forEach(({ programme_book }) => {
      const item = programme_book as OpinionProgrammeBook;
      const programme: w_zgfa = {
        F_XCZDX_REF_ID_: xczdx_ref_id,
        F_ZRBM_: item?.department || '',
        F_ZRLD_: item?.leader || '',
        F_ZJZRR_: item?.user || '',
        F_FAWCSX_: (!!item?.completed_at && dayjs(item?.completed_at).format('YYYY-MM-DD HH:mm:ss')) || '',
        // 调整 TODO...
        F_SFZG_: item?.is_rectification?.toString() || '',
        F_XCJY_: item?.proposal || '',
        F_ZGCS_: item?.measures || '',
        F_FKYJ_ID_: item.uuid,
        ID_: item.uuid,
        REF_ID_: '0',
        PARENT_ID_: '0',
        UPDATE_VERSION_: '',
        INST_ID_: '',
        INST_STATUS_: '',
        TENANT_ID_: '1',
        CREATE_TIME_: now(),
        CREATE_BY_: '',
        UPDATE_BY_: '',
        UPDATE_TIME_: now(),
        CREATE_DEP_ID_: '',
        SERIAL_NUM_: 1,
        DEL_FLAG_: '1',
      };

      // 组织整改方案
      data.w_zgfa.data.push(programme);

      // 业务说明
      // 导出情况只导出已处理状态数据
      // 已处理情况包含所有未通过数据

      // 获取当前节点信息, 节点不存在获取当前分组第一条
      const current_defs = sp_def[NODE_TYPE.PROGRAMME];
      let current_index = 0;
      let current_def;
      // const current_def = item.node ? current_defs[+item.node] : current_defs[0];
      if (item.node) {
        current_index = current_defs.findIndex(_item => String(_item.ID_) === String(item.node));
        current_def = current_defs[current_index];
      }
      else {
        current_def = current_defs[current_index];
      }

      const next = current_defs[current_index + 1];

      // 节点ID
      const node_id = (!!item.node_id && item.node_id) || (uuidv4());
      // 关联ID
      const rel_id = item.uuid;
      // 审核记录ID
      const history_id = uuidv4();

      // 初始状态
      let state = item.state ? (item.state as INodeState) : INodeState.WAIT;

      // 状态未通过
      const fail = [INodeState.FAIL, INodeState.AGAIN_FAIL];

      if (fail.includes(state))
        state = INodeState.AGAIN_WAIT;

      // 组织流程节点
      data.w_sp_node.data.push({
        F_REL_ID_: rel_id,
        F_DEF_ID_: current_def?.ID_ || '',
        F_GROUP_ID_: current_def?.F_GROUP_ID_ || '',
        F_GROUP_NAME_: current_def?.F_GROUP_NAME_ || '',
        F_GROUP_KEY_: current_def?.F_GROUP_KEY_ || '',
        F_STATE_: state,
        F_SFDQJD_: '1',
        F_NEXT_: (next && next.ID_) || '',
        F_TYPE_: NODE_TYPE.PROGRAMME,
        ID_: node_id,
        REF_ID_: '0',
        PARENT_ID_: '0',
        UPDATE_VERSION_: '',
        INST_ID_: '',
        INST_STATUS_: '',
        TENANT_ID_: '1',
        CREATE_TIME_: now(),
        CREATE_BY_: '',
        UPDATE_BY_: '',
        UPDATE_TIME_: now(),
        CREATE_DEP_ID_: '',
        SERIAL_NUM_: 1,
        DEL_FLAG_: '1',
      });

      // 组织审批记录
      data.w_sp_history.data.push({
        F_XCZDX_REF_ID_: xczdx_ref_id,
        F_SPYJ_: '',
        F_SPSM_: '',
        F_SMCL_: '',
        F_FSSJ_: now(),
        F_NODE_ID_: node_id,
        F_RELID_: rel_id,
        F_TYPE_: NODE_TYPE.PROGRAMME,
        F_SHDW_: '',
        F_SHR_: '',
        F_SHDWMC_: '',
        F_SHRMC_: '',
        ID_: history_id,
        REF_ID_: '0',
        PARENT_ID_: '0',
        UPDATE_VERSION_: '',
        INST_ID_: '',
        INST_STATUS_: '',
        TENANT_ID_: '1',
        CREATE_TIME_: now(),
        CREATE_BY_: '',
        UPDATE_BY_: '',
        UPDATE_TIME_: now(),
        CREATE_DEP_ID_: '',
        SERIAL_NUM_: 1,
        DEL_FLAG_: '1',
      });

      const {
        F_FKYJ_ID_,
        F_ZRBM_,
        F_ZRLD_,
        F_ZJZRR_,
        F_FAWCSX_,
        F_SFZG_,
        F_XCJY_,
        F_ZGCS_,
      } = programme;
      data.w_zgfa_ls.data.push({
        F_SP_HISTORY_ID_: history_id,
        F_FKYJ_ID_,
        F_ZRBM_,
        F_ZRLD_,
        F_ZJZRR_,
        F_FAWCSX_,
        F_SFZG_,
        F_XCJY_,
        F_ZGCS_,
        ID_: uuidv4(),
        REF_ID_: '',
        PARENT_ID_: '',
        UPDATE_VERSION_: '',
        INST_ID_: '',
        INST_STATUS_: '',
        TENANT_ID_: '',
        CREATE_TIME_: now(),
        CREATE_BY_: '',
        UPDATE_BY_: '',
        UPDATE_TIME_: now(),
        CREATE_DEP_ID_: '',
        SERIAL_NUM_: 0,
        DEL_FLAG_: '',
      });
    });

    return Promise.resolve(data);
  }
}
